package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.comon.ResultInfo;
import com.itheima.reggie.comon.UserHolder;
import com.itheima.reggie.domain.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @author 七安
 * @description 针对表【shopping_cart(购物车)】的数据库操作Service实现
 * @createDate 2022-08-15 16:15:26
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart>
        implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;


    //添加到购物车
    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        //查询是否在数据库中存在
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                .eq(ShoppingCart::getUserId, UserHolder.get().getId());
        ShoppingCart sc = shoppingCartMapper.selectOne(wrapper);
        //如果不为空的话,就++
        if (sc != null) {
            sc.setNumber(sc.getNumber() + 1);
            //更新数据库
            shoppingCartMapper.updateById(sc);
            return sc;
        } else {
            //不存在就添加
            shoppingCart.setUserId(UserHolder.get().getId());
            shoppingCart.setNumber(1);
            shoppingCartMapper.insert(shoppingCart);
            return shoppingCart;
        }
    }

    @Override
    public ShoppingCart subCart(ShoppingCart shoppingCart) {
        //根据菜品或套餐id查询
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        ShoppingCart sc = shoppingCartMapper.selectOne(wrapper);
        if (sc.getNumber() > 0) {
            sc.setNumber(sc.getNumber() - 1);
            //更新数据库
            shoppingCartMapper.updateById(sc);
            if (sc.getNumber() <= 0) {
                //直接删除
                shoppingCartMapper.deleteById(sc);
            }
        }
        return sc;
    }
}




